package org.eclipse.epsilon.emc.jdt2;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.epsilon.common.parse.AST;
import org.eclipse.epsilon.eol.exceptions.EolRuntimeException;
import org.eclipse.epsilon.eol.execute.context.IEolContext;
import org.eclipse.jdt.core.IJavaProject;

public class QuickSelectOneOperation extends QuickSelectOperationBase {

	public QuickSelectOneOperation(String type, ASTReflection astModel,
			List<IJavaProject> javaProjects) {
		super(type, astModel, javaProjects);
	}

	@Override
	public Object execute(Object target, AST operationAst, IEolContext context)
			throws EolRuntimeException {
		if (target instanceof QuickList) {
			ArrayList<Object> resultList = new ArrayList<Object>();
			Object result = new Object();

			printAST(operationAst, "");

			if (checkAST(operationAst)) {
				System.out.println("HAS NAME AND GOOD!");
				operationAst = transformedAst(operationAst);
			}

			if (operationAst.getChild(1).getText().equals("=")
					&& (operationAst.getChild(1).getChild(0).getChild(1)
							.getText().equals("name") || operationAst
							.getChild(1).getChild(0).getChild(1).getText()
							.equals("fullName"))) { // only with one name
													// constraint
				String s = (String) context.getExecutorFactory().executeAST(
						operationAst.getChild(1).getChild(1), context);
//				resultList.addAll(SearchUtil.search(type, astModel,
//						javaProjects, s, true));
				result = SearchUtil.searchOne(type, astModel,
						javaProjects, s, true);
			} else if (checkAST(operationAst)) { // can use search engine
				operationAst = transformedAst(operationAst);
				
				printAST(operationAst, "");
				
				resultList.addAll(SearchUtil.search(type, astModel,
						javaProjects, tmpName, true));
				System.out.println("has name= --- " + resultList.size());
				System.out.println("SUPER EXECUTION NEEDED!");

				tmpName = null;
				return super.execute(resultList, operationAst, context);
			} else { // not have name constraint
				resultList.addAll(SearchUtil.search(type, astModel,
						javaProjects, "*", true));
				System.out.println("not name= --- " + resultList.size());
				System.out.println(operationAst.getFirstChild() + ":"
						+ operationAst.getFirstChild().getNextSibling());
				// return
				// context.getOperationFactory().getOperationFor("select")
				// .execute(resultList, operationAst, context);
				System.out.println("SUPER EXECUTION NEEDED!");

				// System.out.println(operationAst.getChild(1).getChild(0));
				// printAST(operationAst, "");
				return super.execute(resultList, operationAst, context);
			}

			System.out.println("select one, search finished: " + (result != null));
			return result;

		}
		return context.getExecutorFactory().executeAST(
				operationAst.getChild(1).getChild(1), context);
	}

}
